<script setup>
import { ref } from 'vue';
const jsonData = ref([]);

const handleFileChange = (event) => {
  const files = event.target.files;
  jsonData.value = []; // Clear existing data

  if (files.length > 0) {
    Array.from(files).forEach((file) => {
      const reader = new FileReader();

      reader.onload = (e) => {
        const xmlString = e.target.result;
        const parser = new DOMParser();
        const xmlDoc = parser.parseFromString(xmlString, "text/xml");

        // Parse XML to JavaScript Object
        const extractedData = extractData(xmlDoc);
        for (let i = 0; i < extractedData.length; i++) {
          jsonData.value.push(extractedData[i]);
        }
      };
      reader.onerror = (error) => {
        console.error("Error reading file:", error);
      };

      reader.readAsText(file);
    });
  }
  jsonData.value = jsonData.value.flat();
};

const extractData = (xmlDoc) => {
  const dataElements = xmlDoc.querySelectorAll("Data");
  const result = [];

  dataElements.forEach(dataElement => {
    const code = dataElement.getAttribute("Code");
    const corpOrderID = dataElement.getAttribute("CorpOrderID");

    if (code && corpOrderID) {
      result.push({ Code: code, CorpOrderID: corpOrderID });
    }
  });

  return result;
};
</script>

<template>
  <div>
    <input type="file" @change="handleFileChange" accept=".xml" multiple />
    <pre>{{ jsonData }}</pre>
  </div>
</template>

<style scoped lang="scss">

</style>
